package com.diankangwo.factory.controller;

import cn.beecloud.BCEumeration;
import cn.beecloud.bean.BCRefund;
import com.diankangwo.common.annotation.SysLog;
import com.diankangwo.common.utils.PageUtils;
import com.diankangwo.common.utils.Query;
import com.diankangwo.common.utils.R;
import com.diankangwo.common.validator.ValidatorUtils;
import com.diankangwo.common.validator.group.UpdateGroup;
import com.diankangwo.factory.dao.TdOrderMapper;
import com.diankangwo.factory.dao.TdUserinfoMapper;
import com.diankangwo.factory.dto.TdPortDTO;
import com.diankangwo.factory.dto.TdPortDTOTwo;
import com.diankangwo.factory.dto.TdUserInfoDTO2;
import com.diankangwo.factory.entity.*;
import com.diankangwo.factory.service.TdPortPayLogService;
import com.diankangwo.factory.service.TdPortService;
import com.diankangwo.factory.service.TdPortSettingService;
import com.diankangwo.factory.service.TdUserInfoService;
import com.diankangwo.util.BeecloudPayUtil;
import com.diankangwo.util.EntityDtoConverter;
import com.diankangwo.util.OrderUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * 端口Controller
 * Created by wuye on 2017/9/13.
 */
@RestController
@RequestMapping("/fac/port")
public class TdPortController {

    @Autowired
    private TdPortService tdPortService;

    @Autowired
    private TdUserInfoService tdUserInfoService;

    @Autowired
    private TdUserinfoMapper tdUserinfoMapper;

    @Autowired
    private TdPortSettingService tdPortSettingService;

    @Autowired
    private TdPortPayLogService tdPortPayLogService;

    @Autowired
    private TdOrderMapper tdOrderMapper;

    /**
     * 获取端口列表
     */
    @ApiOperation(value = "根据条件获取端口列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping("/list")
    @RequiresPermissions("fac:port:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<TdPort> tdPortList = tdPortService.queryList(query);
        List<TdPortDTO> tdPortDTOList = new ArrayList<TdPortDTO>();
        //为DTO赋值，并查询出用户信息参数
        for (TdPort port : tdPortList) {
            TdPortDTO tpd = new TdPortDTO();
            EntityDtoConverter edc = new EntityDtoConverter();
            try {
                tpd = (TdPortDTO) edc.entityConvertDto(port, tpd);
                tpd.setUser(tdUserinfoMapper.selectByPrimaryKey(port.getUserid()));
                tdPortDTOList.add(tpd);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        int total = tdPortService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tdPortDTOList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

//    /**
//     * 添加端口（批量）
//     *
//     * @param tdPortList
//     * @return
//     */
//    @ApiOperation(value = "添加端口（批量）", notes = "")
//    @ApiImplicitParam(name = "tdPortList", value = "端口对象", required = true, dataType = "List<TdPort>")
//    @RequestMapping("/list")
//    @RequiresPermissions("fac:port:savelist")
//    public R savelist(@RequestBody List<TdPort> tdPortList) {
//
//        if (tdPortList != null) {
//            for (int i = 0; i <= tdPortList.size(); i++) {
//                tdPortService.save(tdPortList.get(i));
//            }
//        }
//        return R.ok();
//    }

    /**
     * 添加端口
     *
     * @param tdPortDto
     * @return
     */
    @ApiOperation(value = "添加端口", notes = "")
    @ApiImplicitParam(name = "tdPort", value = "端口对象", required = true, dataType = "TdPortDTO")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RequiresPermissions("fac:port:save")
    public R save(@RequestBody TdPortDTOTwo tdPortDto) throws InvocationTargetException, IllegalAccessException {
        if (tdPortDto.getNumber() > 0) {
            TdPortSetting tdPortSetting = tdPortSettingService.selectByPrimaryKey(1);
            for (int i = 0; i < tdPortDto.getNumber(); i++) {
                EntityDtoConverter ed = new EntityDtoConverter();
                TdPort tdPort = new TdPort();
                tdPort = (TdPort) ed.DtoConvertEntity(tdPortDto, tdPort);
                tdPort.setBuytime(new Date());
                tdPort.setMoney((float) tdPortSetting.getPortprice());
                tdPort.setPrice((float) tdPortSetting.getPorttransferprice());
                tdPort.setPresentValue((float) tdPortSetting.getPortprice());
                tdPort.setShoppingprice((float) tdPortSetting.getPortprice());
                tdPort.setReviewstatus("");
                tdPort.setEnabled(false);
                tdPort.setPortid(UUID.randomUUID().toString());
                tdPort.setUserid(tdUserInfoService.selectByPhone(tdPort.getTel()).getId());
                tdPortService.save(tdPort);
                TdUserinfo userinfo = tdUserInfoService.queryById(tdPort.getUserid());
                userinfo.setIsport(true);
                tdUserInfoService.update(userinfo);
            }
        }
        return R.ok();
    }


    /**
     * 修改端口
     */
    @ApiOperation(value = "修改端口", notes = "")
    @ApiImplicitParam(name = "tdPort", value = "修改端口", required = true, dataType = "TdPort")
    @SysLog("修改商品")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @RequiresPermissions("fac:port:update")
    public R update(@RequestBody TdPort tdPort) {
        ValidatorUtils.validateEntity(tdPort, UpdateGroup.class);
        String url = "";
        if (tdPort.getReviewstatus().equals("通过")) {
            tdPort.setType("已审核");
            tdPort.setReviewstatus("通过");
            tdPortService.update(tdPort);
        } else if (tdPort.getReviewstatus().equals("拒绝")) {
            //执行退款操作
            TdPortPayLog tdPortPayLog = tdPortPayLogService.selectByPortId(tdPort.getId());
            TdRefundMoney tdRefundMoney = new TdRefundMoney();
            TdUserinfo tdUserinfo = tdUserInfoService.queryById(tdPort.getUserid());
            tdRefundMoney.setCreatedate(new Date());
            tdRefundMoney.setFundcause(tdPort.getNoreviewdetail());
            tdRefundMoney.setMoney(tdPortPayLog.getPrice());
            tdRefundMoney.setPaymenorderno(tdPortPayLog.getOrderno());
            tdRefundMoney.setState(0);
            tdRefundMoney.setName(tdUserinfo.getName());
            tdRefundMoney.setRefundno(OrderUtil.getNumberForPK());
            tdRefundMoney.setPhonenumber(tdUserinfo.getTel());
            tdRefundMoney.setExamineflow(0);
            TdPort tdPort1 = tdPortService.queryById(tdPortPayLog.getPortid());
            BeecloudPayUtil util = new BeecloudPayUtil();
            BCRefund bcRefund = new BCRefund();
            Map<String, Object> map = new HashMap<>();
            map.put("orderNo", tdPortPayLog.getOrderno());
            TdOrder tdOrder = tdOrderMapper.queryByOrderNo(tdPortPayLog.getOrderno());
            if (tdOrder.getPaytype().equals("ALI_APP")) {
                bcRefund = util.BCRefundParamter(tdRefundMoney.getPaymenorderno(), tdRefundMoney.getRefundno(), tdRefundMoney.getMoney(), BCEumeration.PAY_CHANNEL.ALI, map);
            } else {
                bcRefund = util.BCRefundParamter(tdRefundMoney.getPaymenorderno(), tdRefundMoney.getRefundno(), tdRefundMoney.getMoney(), BCEumeration.PAY_CHANNEL.WX, map);
            }
            url = bcRefund.getAliRefundUrl();
            tdPortService.delete(tdPort1.getId());
            return R.ok().put("url", url);
        }

        return R.ok();
    }

    /**
     * 获取端口申请列表
     */
    @ApiOperation(value = "获取端口申请列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping("/apply")
    @RequiresPermissions("fac:port:apply")
    public R apply(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<TdPort> tdPortList = tdPortService.queryListApply(query);
        List<TdPortDTO> tdPortDTOList = new ArrayList<TdPortDTO>();
        //为DTO赋值，并查询出用户信息参数
        for (TdPort port : tdPortList) {
            TdPortDTO tpd = new TdPortDTO();
            EntityDtoConverter edc = new EntityDtoConverter();
            try {
                tpd = (TdPortDTO) edc.entityConvertDto(port, tpd);
                tpd.setUser(tdUserinfoMapper.selectByPrimaryKey(port.getUserid()));
                tdPortDTOList.add(tpd);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        int total = tdPortService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tdPortDTOList, tdPortDTOList.size(), query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 删除端口
     */
    @ApiOperation(value = "删除端口", notes = "")
    @ApiImplicitParam(name = "portId", value = "端口ID", required = true, dataType = "Integer")
    @SysLog("删除端口")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @RequiresPermissions("fac:port:delete")
    public R delete(Integer id) {
        TdPort tdPort = tdPortService.queryById(id);
        List<TdPort> tdPorts = tdPortService.queryByUserId(tdPort.getUserid());
        tdPortService.delete(id);
        if (tdPorts.size() == 0) {
            TdUserinfo userinfo = tdUserInfoService.queryById(tdPort.getUserid());
            userinfo.setIsport(false);
            tdUserInfoService.update(userinfo);
        }
        return R.ok();
    }


    /**
     * 根据ID查询
     *
     * @return
     */
    @ApiOperation(value = "根据ID查询", notes = "")
    @ApiImplicitParam(name = "id", value = "端口ID", required = true, dataType = "Integer")
    @SysLog("根据ID查询")
    @RequestMapping("/queryById")
    @RequiresPermissions("fac:port:queryById")
    public R queryById(@PathVariable int id) {
        TdPort tdPort = tdPortService.queryById(id);
        return R.ok().put("TdPort", tdPort);
    }

    /**
     * 获取端口用户列表
     */
    @ApiOperation(value = "获取端口用户列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping("/listuser")
    @RequiresPermissions("fac:port:listuser")
    public R listuser(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<TdUserinfo> tdUserinfos = tdUserInfoService.queryListUser(query);
        if (tdUserinfos.size() > 0) {
            List<TdUserInfoDTO2> tdUserInfoDTO2s = new ArrayList<>();
            for (int i = 0; i < tdUserinfos.size(); i++) {
                TdUserInfoDTO2 tuid = new TdUserInfoDTO2();
                tuid.setUserinfo(tdUserinfos.get(i));
                List<TdPort> tdPorts = tdPortService.queryByUserId(tdUserinfos.get(i).getId());
                if (tdPorts.size() > 0) {
                    tuid.setPortNo(tdPorts.size());
                    tuid.setSumMoney(tdPorts.get(0).getPresentValue() * tdPorts.size());
                    tdUserInfoDTO2s.add(tuid);
                }
            }
            int total = tdUserInfoService.queryTotal3(query);

            PageUtils pageUtil = new PageUtils(tdUserInfoDTO2s, total, query.getLimit(), query.getPage());
            return R.ok().put("page", pageUtil);
        } else {
            return R.ok();
        }
    }

    /**
     * 查询用户上下级
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "查询用户上下级", notes = "")
    @RequestMapping("/level")
    @RequiresPermissions("fac:port:level")
    public R level(int userId) {
        TdUserinfo tdUserinfo = tdUserInfoService.queryById(userId);
        if (tdUserinfo != null) {
            //查询上级
            TdUserinfo parent = tdUserInfoService.queryById(tdUserinfo.getParentid());
            //查询下级
            Map<String, Object> params = new HashMap<>();
            params.put("parentId", tdUserinfo.getId());
            List<TdUserinfo> userinfoList = tdUserInfoService.queryByParentId(params);
            return R.ok().put("parent", parent).put("userinfoList", userinfoList);
        }
        return R.error("未查询到用户信息！");
    }

    /**
     * 查询端口交易日志
     * userId  用户ID
     * portId  端口ID
     * orderNo 订单号
     *
     * @return
     */
    @ApiOperation(value = "查询端口交易日志", notes = "")
    @RequestMapping("/paylog")
    @RequiresPermissions("fac:port:paylog")
    public R paylog(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<TdPortPayLog> portPayLogList = tdPortPayLogService.queryList(query);
        int total = tdPortPayLogService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(portPayLogList, total, query.getLimit(), query.getPage());
        return R.ok().put("payLog", pageUtil);
    }

}
